package com.si.anddos;

import java.io.IOException;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.si.anddos.dpadapters.AnddosDbAdapter;
import com.si.anddos.library.main.DownloadProviderThread;

/**
 * A class representing detail of individual download file
 * 
 * @author Carlos Martinez
 * 
 */

public class DownloadDetailActivity extends OptionsMenuActivity {
	private static final int TIME_DIALOG_ID = 0;
	private static final int DATE_DIALOG_ID = 1;
	// private static final int PRIORITY_DIALOG_ID = 2;

	private Spinner spinnerDownloadDetailAccounts;

	private TextView textFileName;
	private TextView textStatus;
	private long downloadId;
	private AnddosDbAdapter dbAdapter;

	private Button buttonPickDate;
	private int pickDay;
	private int pickYear;
	private int pickMonth;

	private Button buttonPickTime;
	private int pickHour;
	private int pickMinute;

	private Spinner spinnerSetPriority;

	private ToggleButton buttonStartStop;
	private Button buttonSave;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.download_detail);
		setTitle(R.string.titleDetailDownload);

		Bundle extras = getIntent().getExtras();
		downloadId = extras != null ? extras
				.getLong(AnddosDbAdapter.colDownloadID) : null;

		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nm.cancel((int)downloadId);

		textFileName = (TextView) findViewById(R.id.textFileName);
		textStatus = (TextView) findViewById(R.id.textStatus);

		spinnerDownloadDetailAccounts = (Spinner) findViewById(R.id.spinnerDownloadDetailAccounts);

		// listener for pick date button
		buttonPickDate = (Button) findViewById(R.id.buttonDownloadDetailPickDate);
		buttonPickDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		

		// listener for pick time button
		buttonPickTime = (Button) findViewById(R.id.buttonDownloadDetailPickTime);
		buttonPickTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});

		// spinner for set priority
		spinnerSetPriority = (Spinner) findViewById(R.id.spinnerDownloadDetailPriority);

		buttonStartStop = (ToggleButton) findViewById(R.id.buttonDownloadDetailStartStop);
		buttonStartStop.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (buttonStartStop.isChecked()) {
					save(AnddosDbAdapter.StatusWaiting);
					setResult(RESULT_OK);
					finish();
			        
			        if (!DownloadProviderService.running) {
			        	Intent service = new Intent(getApplicationContext(), DownloadProviderService.class);
			        	getApplicationContext().startService(service);
			        }
				} else {
					save(AnddosDbAdapter.StatusStopped);
					setResult(RESULT_OK);
					finish();
					DownloadProviderThread.stopDownload(downloadId);
				}
			}
		});

		// on click listener for button save
		buttonSave = (Button) findViewById(R.id.buttonDownloadDetailSave);
		buttonSave.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				save(-1);
				setResult(RESULT_OK);
				finish();
			}
		});

		// create accounts db adapter

		dbAdapter = new AnddosDbAdapter(this);
		
	}
	
	@Override
	public void onBackPressed() {
		setResult(RESULT_OK);
		finish();
	}
	protected void onResume() {
		super.onResume();
		// populate download detail from db to activity
		fillData();
	}

	private void fillData() {
		dbAdapter.open();
		Cursor downloadDetail = dbAdapter.getDownload(downloadId);
		startManagingCursor(downloadDetail);

		Cursor account = dbAdapter.getAllAccounts();
		startManagingCursor(account);

		String url = downloadDetail.getString(downloadDetail
				.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadUrl));
		textFileName.setText(url);

		// Create an array to specify the fields we want to display in the list
		// (only TITLE)
		String[] from = new String[] { AnddosDbAdapter.colAccountUsername,
				AnddosDbAdapter.colAccountService };

		// and an array of the fields we want to bind those fields to (in this
		// case just text1)
		int[] to = new int[] { R.id.textAccountRow, R.id.textAccountRowService };

		spinnerDownloadDetailAccounts.setAdapter(new SimpleCursorAdapter(this,
				R.layout.account_list_row, account, from, to));

		long detailAccount = downloadDetail.getLong(downloadDetail
				.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadAccount));

		for (int i = 0; i < spinnerDownloadDetailAccounts.getCount(); i++) {
			Cursor value = (Cursor) spinnerDownloadDetailAccounts
					.getItemAtPosition(i);
			long id = value.getLong(value.getColumnIndexOrThrow("_id"));
			if (id == detailAccount) {
				spinnerDownloadDetailAccounts.setSelection(i);
			}
		}

		// disable spinner if no accounts is in database
		if (account.getCount() == 0)
			spinnerDownloadDetailAccounts.setEnabled(false);

		// load time and from database of item download file
		String dateTime = downloadDetail.getString(downloadDetail
				.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadDateTime));
		Time tDateTime = new Time();
		tDateTime.parse(dateTime);
		pickYear = tDateTime.year;
		pickMonth = tDateTime.month;
		pickDay = tDateTime.monthDay;
		pickHour = tDateTime.hour;
		pickMinute = tDateTime.minute;

		ArrayAdapter<CharSequence> adapterPrioritys = ArrayAdapter
				.createFromResource(this, R.array.prioritys,
						android.R.layout.simple_spinner_item);
		adapterPrioritys
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerSetPriority.setAdapter(adapterPrioritys);

		int priority = downloadDetail.getInt(downloadDetail
				.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadPriority));
		switch (priority) {
		case AnddosDbAdapter.PriorityLow:
			spinnerSetPriority.setSelection(AnddosDbAdapter.PriorityLow);
			break;
		case AnddosDbAdapter.PriorityNormal:
			spinnerSetPriority.setSelection(AnddosDbAdapter.PriorityNormal);
			break;
		case AnddosDbAdapter.PriorityHigh:
			spinnerSetPriority.setSelection(AnddosDbAdapter.PriorityHigh);
			break;
		}

		// display the current date
		updateButtonDownloadDateDisplay();
		// display the loaded time
		updateButtonDownloadTimeDisplay();

		int status = downloadDetail.getInt(downloadDetail
				.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadStatus));
		this.textStatus.setText(this.getStatusString(status));
		//System.out.println(this.textStatus.getText());
		if (status == AnddosDbAdapter.StatusProcessing || status == AnddosDbAdapter.StatusDone) {
			buttonStartStop.setChecked(true);
			buttonStartStop.setEnabled(false);
			spinnerDownloadDetailAccounts.setEnabled(false);
			buttonPickDate.setEnabled(false);
			buttonPickTime.setEnabled(false);
			spinnerSetPriority.setEnabled(false);
			buttonSave.setEnabled(false);
		}
		dbAdapter.close();
	}
	
	private String getStatusString(int status) {
    	if (status == AnddosDbAdapter.StatusWaiting) {
    		this.textStatus.setTextColor(0xffffff00);
    		return " Waiting";
    	} else if (status == AnddosDbAdapter.StatusProcessing) {
    		this.textStatus.setTextColor(0xff0000ff);
    		return " Processing";
    	} else if (status == AnddosDbAdapter.StatusError) {
    		this.textStatus.setTextColor(0xffff0000);
    		return " Error";
    	} else if (status == AnddosDbAdapter.StatusDone) {
    		this.textStatus.setTextColor(0xff00ff00);
    		return " Done";
    	} else if (status == AnddosDbAdapter.StatusStopped) {
    		this.textStatus.setTextColor(0xff888888);
    		return " Stopped";
    	} else {
    		return "";
    	}
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			pickYear = year;
			pickMonth = monthOfYear;
			pickDay = dayOfMonth;
			updateButtonDownloadDateDisplay();
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			pickHour = hourOfDay;
			pickMinute = minute;
			updateButtonDownloadTimeDisplay();
		}
	};

	private void updateButtonDownloadDateDisplay() {
		// updates the date we display as the text in button
		buttonPickDate.setText(new StringBuilder()
				// Month is 0 based so add 1
				.append(pickMonth + 1).append("-").append(pickDay).append("-")
				.append(pickYear).append(" "));
	}

	private void updateButtonDownloadTimeDisplay() {
		// updates the time we display as the text in button
		buttonPickTime.setText(new StringBuilder().append(pad(pickHour))
				.append(":").append(pad(pickMinute)));
	}

	private static String pad(int c) {
		// adding zeros for correct time viewing
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	protected Dialog onCreateDialog(int id) {
		// creating time picker dialog
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, pickYear,
					pickMonth, pickDay);
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, pickHour,
					pickMinute, true);
		}
		return null;
	}

	private void save(int stateStatus) {
		dbAdapter.open();
		Cursor downloadDetail = dbAdapter.getDownload(downloadId);
		startManagingCursor(downloadDetail);

		Time dateTime = new Time();
		dateTime.set(0, pickMinute, pickHour, pickDay, pickMonth, pickYear);

		String url = downloadDetail.getString(downloadDetail
				.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadUrl));
		String[] items = url.split("/");
		String fileName = items[items.length - 1];

		long accountId = spinnerDownloadDetailAccounts.getSelectedItemId();

		int id = downloadDetail.getInt(downloadDetail
				.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadID));

		// na lepsi prevod jsem neprisel
		long priorityIdLong = spinnerSetPriority.getSelectedItemId();
		String priorityIdString = Long.toString(priorityIdLong);
		int priority = Integer.parseInt(priorityIdString);
//
//		int cache = 10;
//		if (stateStatus == "start")
//			cache = 1;
//		if (stateStatus == "stop")
//			cache = 4;
//		if (stateStatus == "save") {
		int status = downloadDetail.getInt(downloadDetail
					.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadStatus));
		
		if (status != stateStatus) {
			status = stateStatus;
		}
//		}
//		int status = cache;
		// save download to database
		dbAdapter.updateDownload(id, dateTime, url, fileName, status, priority,
				accountId);
		dbAdapter.close();
	}
}
